package com.example.android.story.ui;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.story.R;
import com.example.android.story.Utils.Purchased;
import com.example.android.story.Utils.Story;
import com.example.android.story.Utils.StoryViewModel;
import com.example.android.story.Utils.User;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private StoryViewModel mViewModel;
    private User mUser;
    private static Intent intent=new Intent();
    LiveData<List<Story>> mAllStories;
    LiveData<List<Story>> mMyStories;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setUpViewModel();

        setUpPager();

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }

        intent=new Intent(MainActivity.this,UnityPlayerActivity.class);
    }

    private void setUpPager() {
        ViewPager pager = findViewById(R.id.pager);
        pager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
    }

    private void setUpViewModel() {
        mViewModel = ViewModelProviders.of(this).get(StoryViewModel.class);

        Intent intent = getIntent();
        final String username = intent.getStringExtra("username");
        mViewModel.getAllUsers().observe(this, new Observer<List<User>>() {
            @Override
            public void onChanged(@Nullable List<User> users) {
                for (User u : users) {
                    if (u.getName().equals(username)) {
                        NavigationView nav_view = findViewById(R.id.nav_view);
                        View hear_view = nav_view.getHeaderView(0);
                        TextView usernameText = (TextView) hear_view.findViewById(R.id.username);
                        mUser = u;
                        usernameText.setText(mUser.getName());
                    }
                }
            }
        });
        mAllStories = mViewModel.getAllStories();
        NavigationView nav_view = findViewById(R.id.nav_view);
        nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if(item.getItemId()==R.id.nav_upload){
                    Intent intent=new Intent();
                    intent.setClass(MainActivity.this,UploadActivity.class);
                    startActivity(intent);
                }
                return true;
            }
        });

        loadMyStories(username);
    }

    private void loadMyStories(String username) {
        final MutableLiveData<List<Story>> mystories = new MutableLiveData<>();
        mMyStories=mystories;
        final LiveData<List<Purchased>> purchased = mViewModel.getPurchased(username);
        purchased.observe(this, new Observer<List<Purchased>>() {
            @Override
            public void onChanged(@Nullable List<Purchased> purchaseds) {
                if(purchased==null)
                    return ;
                ArrayList<Story> list=new ArrayList<>();
                for(Purchased p: purchaseds){
                    Story story=mViewModel.getStories(p.story_title);
                    list.add(story);
                }
                mystories.setValue(list);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
        }
        return true;
    }

    public class PagerAdapter extends FragmentPagerAdapter {

        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            if (position == 0) {
                StoryListFragment fragment=new StoryStoreFragment();
                fragment.setStories(mAllStories);
                return fragment;
            }
            else {
                StoryListFragment fragment=new PurchasedStoryFragment();
                fragment.setStories(mMyStories);
                return fragment;
            }
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if (position == 0)
                return "Story Store";
            else
                return "My Stories";
        }
    }

    public static abstract class StoryListFragment extends Fragment {


        private LiveData<List<Story>> mStories = null;
        private StoryAdapter mStoryAdapter;

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.story_store, container, false);
            return view;
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            mStoryAdapter=createAdapter();
            final RecyclerView recyclerView = getView().findViewById(R.id.recyclerView);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(mStoryAdapter);
            if (mStories != null)
                mStories.observe(getActivity(), new Observer<List<Story>>() {
                    @Override
                    public void onChanged(@Nullable List<Story> stories) {
                        if(stories!=null) {
                            mStoryAdapter.setStories(stories);
                            recyclerView.setAdapter(null);
                            recyclerView.setAdapter(mStoryAdapter);
                        }
                    }
                });
        }

        public abstract StoryAdapter createAdapter() ;

        public void setStories(LiveData<List<Story>> mStories) {
            this.mStories = mStories;
        }
    }

    public static class StoryStoreFragment extends StoryListFragment{

        @Override
        public StoryAdapter createAdapter() {
            return new StoryAdapter( new StoryAdapter.OnItemClickListener() {
                @Override
                public void onClick(Story story) {
                    Toast.makeText(getActivity(), "购买storie:"+story.getTitle(), Toast.LENGTH_SHORT).show();
                    startActivity(intent);
                }
            });
        }
    }
    public static class PurchasedStoryFragment extends  StoryListFragment{

        @Override
        public StoryAdapter createAdapter() {
            return new StoryAdapter( new StoryAdapter.OnItemClickListener() {
                @Override
                public void onClick(Story story) {
                    Toast.makeText(getActivity(),"点击我的storie:"+story.getTitle(),Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}
